import { Breadcrumb, Button, Steps, Result, Space } from 'antd'
import styled from 'styled-components'
import { Link, useNavigate } from 'react-router-dom'
import { useState, useRef } from 'react'
import { addService } from '@/api/sharing/serviceCatalog'
import BaseInfoForm from './modules/BaseInfoForm'
import ApiReQForm from './modules/ApiReQForm'
import BackEndServiceForm from './modules/BackEndServiceForm'

const steps = [
  {
    title: '基本信息',
  },
  {
    title: '定义API请求',
  },
  {
    title: '定义后端服务',
  },
  {
    title: '创建完成',
  },
]

const ServiceCatalogEdit = () => {
  const [current, setCurrent] = useState(0)
  const formRefs = useRef([])
  const navigate = useNavigate()
  const next = () => {
    setCurrent(current + 1)
  }
  const prev = () => {
    setCurrent(current - 1)
  }
  const items = steps.map((item) => ({
    key: item.title,
    title: item.title,
  }))
  const contentStyle = {
    // lineHeight: '260px',
    // textAlign: 'center',
    // color: token.colorTextTertiary,
    // backgroundColor: token.colorFillAlter,
    // borderRadius: token.borderRadiusLG,
    // border: `1px dashed ${token.colorBorder}`,
    // marginTop: 16,
  }
  /* 提交表单操作 */
  const handleSubmitForm = () => {
    Promise.all(
      formRefs.current.map((ref, index) => {
        return ref.validateFields().catch((e) => {
          return Promise.reject({ ...e, index })
        })
      })
    )
      .then(() => {
        const values = formRefs.current.map((ref) => ref.getFieldsValue())
        const formValues = { ...values[0], apiRequestDto: { ...values[1] }, apiServiceDto: { ...values[2] } }
        const options = formRefs.current?.[0]?.options || []
        /* 将选项转换为对象 */
        if (Array.isArray(formValues.labels)) {
          const optionsMap = new Map(options.map((option) => [option.value, option.label]))
          formValues.labels = formValues.labels.reduce((acc, item) => {
            if (optionsMap.has(item)) {
              acc[optionsMap.get(item)] = item
            }
            return acc
          }, {})
        }
        return addService(formValues)
      })
      .then((response) => {
        if (response.code === 200) {
          next()
        }
      })
      .catch((e) => {
        setCurrent(e.index)
      })
  }

  return (
    <StyleWrap>
      <div className="page-breadcrumb">
        <Breadcrumb
          items={[
            {
              title: <Link to="/integration/sharing/serviceCatalog">服务目录</Link>,
            },
            {
              title: '数据编辑',
            },
          ]}
        />
      </div>
      <div className="steps-wrapper">
        <Steps current={current} items={steps} />
      </div>

      <div className="forms-wrapper">
        <BaseInfoForm
          style={{ display: current === 0 ? 'block' : 'none' }}
          ref={(el) => {
            if (el) formRefs.current[0] = el
          }}
        />
        <ApiReQForm
          style={{ display: current === 1 ? 'block' : 'none' }}
          ref={(el) => {
            if (el) formRefs.current[1] = el
          }}
        />
        <BackEndServiceForm
          style={{ display: current === 2 ? 'block' : 'none' }}
          ref={(el) => {
            if (el) formRefs.current[2] = el
          }}
        />
        <Result
          style={{ display: current === 3 ? 'block' : 'none' }}
          status="success"
          title="API服务创建完成!"
          extra={[
            <Button type="primary" key="console" onClick={() => navigate('/integration/sharing/serviceCatalog')}>
              返回服务目录
            </Button>,
          ]}
        />
      </div>

      <div className="buttons-wrapper">
        <Space
          size="large"
          style={{
            marginTop: 24,
            display: current === steps.length - 1 ? 'none' : undefined,
          }}
        >
          <Button disabled={current === 0 || current === steps.length - 1} onClick={() => prev()}>
            上一步
          </Button>
          <Button disabled={current >= steps.length - 2} onClick={() => next()}>
            下一步
          </Button>
          <Button type="primary" onClick={handleSubmitForm}>
            提交
          </Button>
        </Space>
      </div>
    </StyleWrap>
  )
}

const StyleWrap = styled.div`
  padding: 16px;
  .steps-wrapper {
    width: 70%;
  }
  .forms-wrapper {
    margin-top: 30px;
  }
  .buttons-wrapper {
    /* width: 70%; */
    /* text-align: center; */
  }

  .ant-input,
  textarea.ant-input,
  .ant-select {
    max-width: 600px;
  }
  .ant-form-item-label {
    width: 120px;
    text-align: right;
  }
`
export default ServiceCatalogEdit
